<template>
  <!-- 'background-size':!isCover?'contain':'cover' -->
  <div class="login-container" :style="{ 'background-image': background }" :key="`${isCover}`">
    <div class="jvs-home" v-if="loadingShow" style="position: absolute;top: 0;left: 0;width: 100%;height: 100vh;">
      <div class="jvs-home__main">
        <img class="jvs-home__loading_gif" :src="loadingImgSrc" alt="loading">
        <div class="jvs-home__title">
          {{ $t('message.text.lodingResource') }}
        </div>
        <div class="jvs-home__sub-title">
          {{ $t('message.text.initTimeLong') }}
        </div>
      </div>
    </div>
    <div class="lang-change-box">
      <div class="lang-box-item" ref="buttonRef" @click="openVisible">
        <span>{{ currentLang.label }}</span>
        <svg class="icon">
          <use xlink:href="#keowledge-xiala-zhankai"></use>
        </svg>
      </div>
    </div>
    <el-popover ref="popoverRef" :virtual-ref="buttonRef" trigger="click" virtual-triggering :visible="visible"
      popper-class="custom-popper-class lang-popper">
      <div class="lang-list-box" v-click-outside="onClickOutsideLang">
        <el-scrollbar>
          <div class="lang-item" v-for="(item, index) in langList" @click="changeLang(item)" :key="index">
            <span>{{ item.label }}</span>
            <svg class="icon" v-if="item.value === currentLang.value">
              <use xlink:href="#keowledge-xuanzhong"></use>
            </svg>
          </div>
        </el-scrollbar>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  onMounted,
  onBeforeUnmount,
  getCurrentInstance
} from 'vue'
import loadingImg from '@/assets/images/loading.gif'
import { useRouter, useRoute } from "vue-router"
import { getStore } from '@/utils/store.js'
import { useIsMobile } from '@/hooks/common'
import { getDomain } from '@/api/login'
import useSocketStore from '@/store/socket';
import { urlParsParams, getFullUrl } from '@/utils/util'
import { ClickOutside as vClickOutside } from 'element-plus'
import { useHookI18n } from '@/hooks/i18n'
import useCommonStore from '@/store/common'
const { locale, $t } = useHookI18n()
// import bulletinDialog from '@/utils/bulletin.js'
let userInfo = getStore({ name: 'userInfo' })
const router = useRouter();
const route = useRoute();
const loadingImgSrc = loadingImg
const { mobileFlag } = useIsMobile()
const commonStore = useCommonStore()
const sokcetStore = useSocketStore()
const loginQuery = ref('')
const background = ref('background')
const { $loginForm, $openUrl } = getCurrentInstance()?.appContext.config.globalProperties as any
if (userInfo?.id) {
  router.push('/index')
} else if (mobileFlag.value) {
  router.push('/mobile/login')
} else {
  let headList = document.getElementsByTagName('head')[0].children
  for (let i in headList) {
    if (headList[i].type == 'image/x-icon') {
      headList[i].href = " "
    }
  }
  sokcetStore.MESSAGE_CLOSE()
  loginQuery.value = localStorage.getItem('loginQuery') || ''
  // 获取域名相关设置
  getDomainHandle()
}

const emit = defineEmits([""])
const loadingShow = ref(false)
const isCover = ref(true)
const imgObj = ref({
  width: 0,
  height: 0
})
const buttonRef = ref()
const visible = ref(false)
const langList = [{
  label: '简体中文',
  showLabel: '中',
  value: 'zh-CN'
}, {
  label: 'English',
  showLabel: 'EN',
  value: 'en'
}]
const currentLang = ref({
  label: '简体中文',
  showLabel: '中',
  value: 'zh-CN'
})
onMounted(() => {
  // let lang = getStore({name:'lang'})
  // if(!lang){
  //   const navigator = window.navigator
  //   lang = navigator.language.toLowerCase()
  // }
  langList.forEach(item => {
    if (item.value == locale.value) {
      currentLang.value = item
    }
  })
  console.log(currentLang.value)
  // window.addEventListener('resize',bodyResize,true)
})
onBeforeUnmount(() => {
  // window.removeEventListener('resize',bodyResize,true)
})
function bodyResize() {
  if (imgObj.value.width < document.body.clientWidth) {
    isCover.value = false
  } else {
    if (window.screen.width == document.body.clientWidth) {
      isCover.value = false
    } else {
      isCover.value = true
    }
  }
}
function getDomainHandle() {
  background.value = ""
  document.title = ""
  getDomain().then(res => {
    if (res.data && res.data.code == 0) {
      if (res.data.data) {
        if (res.data.data.bgImg) {
          background.value = `url("${res.data.data.bgImg}")`
        }
        var img = new Image();
        img.src = res.data.data.bgImg;

        img.onload = function () {
          imgObj.value.width = img.width
          imgObj.value.height = img.height
          if (img.width < window.document.body.clientWidth) {
            isCover.value = false
          } else {
            if (window.screen.width == document.body.clientWidth) {
              isCover.value = false
            } else {
              isCover.value = true
            }
          }
        }
        if (res.data.data.systemName) {
          document.title = res.data.data.systemName
        }
        if (res.data.data.icon) {
          var link = document.createElement('link')
          link.type = 'image/x-icon'
          link.rel = 'shortcut icon'
          link.href = res.data.data.icon
          document.getElementsByTagName('head')[0].appendChild(link);
        }
        if (!mobileFlag.value) {
          openLogin()
        }
      } else {
        router.push({ path: '/404' });
      }
    } else {
    }
  }).catch(err => {
  })
}
function openLogin() {
  let tp: Array<any> = []
  let qda: { key?: string | Number } = {}
  let qsting = loginQuery.value
  if (qsting && qsting.includes('?')) {
    tp = qsting.split('?')[1].split('&')
  }
  tp.map((item) => {
    let keyv: (Number | String)[] = item.split('=')
    qda[keyv[0]] = keyv[1]
  })
  $loginForm({
    hasModal: false,
    successClose: false,
    queryData: qda ? qda : null,
    right: '245px',
    afterLogin: (res: { userDto: { tenant: { name: string; icon: string } } }) => {
      // 这里是否要打开新的公告提示
      // bulletinDialog.install()
      if (res.userDto?.tenant?.name) {
        document.title = res.userDto.tenant.name
      }
      if (res.userDto.tenant.icon) {
        var link = document.createElement('link')
        link.type = 'image/x-icon'
        link.rel = 'shortcut icon'
        link.href = res.userDto.tenant.icon
        document.getElementsByTagName('head')[0].appendChild(link);
      }
      commonStore.setLang(locale.value)
      loginToPath()
    },
  })
}
// 登陆后跳转
function loginToPath() {
  const knowledgeBroad = new BroadcastChannel('knowledgeMessage')
  knowledgeBroad.postMessage({
    type: 'checkLogin'
  })
  let path = sessionStorage.getItem('lastUrl')
  if (path) {
    $openUrl(path, '_self')
  } else {
    if (route.query.redict_url) {
      const red_url = decodeURIComponent(route.query.redict_url as string)
      let querys = {}
      if (red_url.indexOf('?') != -1) {
        querys = urlParsParams(red_url)
      }
      router.push({
        path: getFullUrl(red_url),
        query: querys
      })
    } else {
      router.push({ path: '/index' });
    }
  }
}
function onClickOutsideLang() {
  visible.value = false
}
function openVisible() {
  visible.value = true
}
function changeLang(item: { label: string; showLabel: string; value: string }) {
  currentLang.value = item
  locale.value = item.value
  commonStore.setLang(item.value)
  // setStore({name:'lang',content:item.value})
  // location.reload()
  visible.value = false
}
</script>
<style lang="scss" scoped>
.login-container {
  display: flex;
  align-items: center;
  position: relative;
  width: 100%;
  height: 100%;
  margin: 0 auto;
  // background-size: cover;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: 50%;
  background-attachment: fixed;
  //   background-position: 50%;
  //   background-attachment: fixed;
}
</style>
<style lang="scss">
.lang-popper {
  z-index: 2014 !important;
}

.lang-change-box {
  position: fixed;
  z-index: 2014;
  bottom: 32px;
  right: 24px;
  min-width: 120px;
  height: 32px;
  background: #F5F6F7;
  border-radius: 4px 4px 4px 4px;
  display: flex;
  align-items: center;
  justify-content: center;

  .lang-box-item {
    display: flex;
    align-items: center;
    cursor: pointer;
    width: max-content;

    span {
      font-size: 14px;
      color: #6f7588;
      // @include SourceHanSansCN-Bold;
    }

    .icon {
      width: 14px;
      height: 14px;
      margin-left: 2px;
    }
  }
}
</style>